package com.ynet.middleground.riskmanage.mq.consumer;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ynet.core.common.BaseReqObj;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.host.HostConstants;
import com.ynet.middleground.riskmanage.dao.WorldexBlchFileMapper;
import com.ynet.middleground.riskmanage.dao.WorldexBlchInMapper;
import com.ynet.middleground.riskmanage.dao.WorldexBlchOutMapper;
import com.ynet.middleground.riskmanage.entity.WorldexBlchIn;
import com.ynet.middleground.riskmanage.entity.WorldexBlchOut;
import com.ynet.middleground.riskmanage.external.MainBusinessConfig;
import com.ynet.middleground.riskmanage.model.worldex.WorldexModel;
import com.ynet.middleground.riskmanage.mq.SinkBlchzt;
import com.ynet.middleground.riskmanage.mq.producer.BlchztProducer;
import com.ynet.middleground.riskmanage.utils.ApiUtil;

/**
 * @ClassName BlchztConsumer
 * @Description 保理池状态消息消费类
 * @Author zhangyongbin
 * @Date 2020/8/20 17:21
 * @Version 1.0
 */
@Component
public class BlchztConsumer {
    @Autowired
    WorldexBlchInMapper worldexBlchInMapper;

    @Autowired
    WorldexBlchOutMapper worldexBlchOutMapper;

    @Autowired
    WorldexBlchFileMapper worldexBlchFileMapper;

    @Autowired
    BlchztProducer producer;

    @Autowired
    ApiUtil apiUtil;

    /**
     * 日志打印时显示的名称
     */
    public static final String LOG_NAME = "全球捷运";

    /**
     * 0 发票；1 费用确认单
     */
    public static final String NUMBER_ZERO = "0";
    public static final String NUMBER_ONE = "1";

    @Autowired
    private MainBusinessConfig mainBusinessConfig;

    /**
     * 消费保理池入池状态消息
     *
     * @param msgMap
     */
    @StreamListener(SinkBlchzt.BLXD_TO_JKZTFK_BLCHZT_IN)
    @Transactional(rollbackFor = Exception.class)
    public void inputBlcztInConsumer(Map<String, Object> msgMap) {
        IfpLogger.info("mq", "MQ 入池状态数据，从 Binding-{}收到信息-{}", SinkBlchzt.BLXD_TO_JKZTFK_BLCHZT_IN, msgMap);

        String traceId = msgMap.get("traceId") == null ? "" : msgMap.get("traceId").toString();
        String requestTime = msgMap.get("requestTime") == null ? "" : msgMap.get("requestTime").toString();
        String channel = msgMap.get("channel") == null ? "" : msgMap.get("channel").toString();
        String orderType = msgMap.get("orderType") == null ? "" : msgMap.get("orderType").toString();
        String orderNum = msgMap.get("orderNum") == null ? "" : msgMap.get("orderNum").toString();
        String serialNo = msgMap.get("serialNo") == null ? "" : msgMap.get("serialNo").toString();
        String status = msgMap.get("status") == null ? "" : msgMap.get("status").toString();
        String reason = msgMap.get("reason") == null ? "" : msgMap.get("reason").toString();
        String newPoolDate = msgMap.get("newPoolDate") == null ? "" : msgMap.get("newPoolDate").toString();
        String currency = msgMap.get("currency") == null ? "" : msgMap.get("currency").toString();

        // update by liwq on 2021-03-11 start
        // 根据单据编号查询入池信息
        if (!NUMBER_ZERO.equals(orderType) && !NUMBER_ONE.equals(orderType)) {
            throw new BusinessException("单据类型有误", "ECCT0703");
        }
        QueryWrapper wrapper = new QueryWrapper();
        // 若是发票，根据单据编号+序列号可确定唯一；
        if (NUMBER_ZERO.equals(orderType)) {
            wrapper.eq("order_num", orderNum);
            wrapper.eq("serial_no", serialNo);
        }
        // 若是费用确认单，根据单据编号+序列号+币种确定唯一；
        if (NUMBER_ONE.equals(orderType)) {
            wrapper.eq("order_num", orderNum);
            wrapper.eq("serial_no", serialNo);
            wrapper.eq("currency", currency);
        }
        WorldexBlchIn worldexBlchIn = null;
        List<WorldexBlchIn> list = worldexBlchInMapper.selectList(wrapper);
        if (list.size() > 0) {
            worldexBlchIn = list.get(0);
        }
        if (worldexBlchIn == null) {
            throw new BusinessException("该保理池业务数据不存在", "ECCT0600");
        }
        // update by liwq on 2021-03-11 end

        // 更新入池信息状态
        worldexBlchIn.setStatus(status);
        worldexBlchIn.setChannel(channel);
        worldexBlchIn.setGmtModified(LocalDateTime.now());
        worldexBlchIn.setReason(reason);
        worldexBlchIn.setNewPoolDate(newPoolDate);
        worldexBlchInMapper.updateById(worldexBlchIn);

        // 查询附件信息
        // QueryWrapper fileWrapper = new QueryWrapper();
        // fileWrapper.eq("order_id", worldexBlchIn.getId());
        // WorldexBlchFile worldexBlchFile = worldexBlchFileMapper.selectOne(fileWrapper);

        // 将更新状态后的入池信息加入消息队列
        // 消息要素
        // Map<String, Object> msgPushMap = new HashMap<>(9);
        // msgPushMap.put("method","jkztfk-to-qqjy-in");
        // msgPushMap.put("traceId", traceId);
        // msgPushMap.put("requestTime", requestTime);
        // msgPushMap.put("orderType", orderType);
        // msgPushMap.put("orderNum", orderNum);
        // msgPushMap.put("serialNo", serialNo);
        // msgPushMap.put("status", status);
        // msgPushMap.put("reason", reason);
        // msgPushMap.put("newPoolDate", newPoolDate);
        msgMap.put("method", "jkztfk-to-qqjy-in");

        // 调用全球捷运接口发送数据
        sendMessagesBlchztIn(msgMap);
    }

    /**
     * 消费保理池出池状态消息
     *
     * @param msgMap
     */
    @StreamListener(SinkBlchzt.BLXD_TO_JKZTFK_BLCHZT_OUT)
    @Transactional(rollbackFor = Exception.class)
    public void inputBlcztOutConsumer(Map<String, Object> msgMap) {
        IfpLogger.info("mq", "MQ 出池状态数据，从 Binding-{}收到信息-{}", SinkBlchzt.BLXD_TO_JKZTFK_BLCHZT_OUT, msgMap);

        String traceId = msgMap.get("traceId") == null ? "" : msgMap.get("traceId").toString();
        String requestTime = msgMap.get("requestTime") == null ? "" : msgMap.get("requestTime").toString();
        String channel = msgMap.get("channel") == null ? "" : msgMap.get("channel").toString();
        String orderType = msgMap.get("orderType") == null ? "" : msgMap.get("orderType").toString();
        String orderNum = msgMap.get("orderNum") == null ? "" : msgMap.get("orderNum").toString();
        String serialNo = msgMap.get("serialNo") == null ? "" : msgMap.get("serialNo").toString();
        String status = msgMap.get("status") == null ? "" : msgMap.get("status").toString();
        String reason = msgMap.get("reason") == null ? "" : msgMap.get("reason").toString();
        String outPoolDate = msgMap.get("outPoolDate") == null ? "" : msgMap.get("outPoolDate").toString();
        String currency = msgMap.get("currency") == null ? "" : msgMap.get("currency").toString();

        // update by liwq on 2021-03-11 start
        // 根据单据编号查询出池信息
        if (!NUMBER_ZERO.equals(orderType) && !NUMBER_ONE.equals(orderType)) {
            throw new BusinessException("单据类型有误", "ECCT0703");
        }
        QueryWrapper wrapper = new QueryWrapper();
        // 若是发票，根据单据编号+序列号可确定唯一；
        if (NUMBER_ZERO.equals(orderType)) {
            wrapper.eq("order_num", orderNum);
            wrapper.eq("serial_no", serialNo);
        }
        // 若是费用确认单，根据单据编号+序列号+币种确定唯一；
        if (NUMBER_ONE.equals(orderType)) {
            wrapper.eq("order_num", orderNum);
            wrapper.eq("serial_no", serialNo);
            wrapper.eq("currency", currency);
        }
        WorldexBlchOut worldexBlchOut = null;
        List<WorldexBlchOut> list = worldexBlchOutMapper.selectList(wrapper);
        if (list.size() > 0) {
            worldexBlchOut = list.get(0);
        }
        if (worldexBlchOut == null) {
            throw new BusinessException("该保理池业务数据不存在", "ECCT0600");
        }
        // update by liwq on 2021-03-11 end

        // 更新出池信息状态
        worldexBlchOut.setStatus(status);
        worldexBlchOut.setChannel(channel);
        worldexBlchOut.setGmtModified(LocalDateTime.now());
        worldexBlchOut.setReason(reason);
        worldexBlchOut.setOutPoolDate(outPoolDate);
        worldexBlchOutMapper.updateById(worldexBlchOut);

        // //查询附件信息
        // QueryWrapper fileWrapper = new QueryWrapper();
        // fileWrapper.eq("order_id", worldexBlchOut.getId());
        // WorldexBlchFile worldexBlchFile = worldexBlchFileMapper.selectOne(fileWrapper);

        // 将更新状态后的出池信息加入消息队列
        // 消息要素
        // Map<String, Object> msgPushMap = new HashMap<>(8);
        // msgPushMap.put("traceId",traceId);
        // msgPushMap.put("requestTime", requestTime);
        // msgPushMap.put("orderType", orderType);
        // msgPushMap.put("orderNum", orderNum);
        // msgPushMap.put("serialNo", serialNo);
        // msgPushMap.put("status", status);
        // msgPushMap.put("reason", reason);
        // msgPushMap.put("outPoolDate", outPoolDate);
        msgMap.put("method", "jkztfk-to-qqjy-out");

        sendMessagesBlchztOut(msgMap);
    }

    public void sendMessagesBlchztIn(Map<String, Object> params) {

        BaseReqObj baseReqObj = new BaseReqObj();
        baseReqObj.setOperationUserId(1);
        baseReqObj.setChannel((String)params.get("channel"));

        JSONObject apiResult =
            apiUtil.sendApiLog("2001", mainBusinessConfig.getWorldexUrl() + WorldexModel.URL_PUSH_BLCH_STATUS, null,
                params, HostConstants.HTTP_METHOD_POST, LOG_NAME, baseReqObj);

        // JSONObject apiResult = JSONObject.parseObject("{\"code\": 0, \t\"msg\": \"操作成功\", \t\"debug\": \"详细错误提示\"
        // }");

        Integer code = apiResult.getInteger("code");
        String message = apiResult.getString("msg");
        if (!code.equals(0)) {
            throw new BusinessException(message, String.valueOf(code));
        }
    }

    public void sendMessagesBlchztOut(Map<String, Object> params) {

        BaseReqObj baseReqObj = new BaseReqObj();
        baseReqObj.setOperationUserId(1);
        baseReqObj.setChannel((String)params.get("channel"));

        JSONObject apiResult =
            apiUtil.sendApiLog("2002", mainBusinessConfig.getWorldexUrl() + WorldexModel.URL_PUSH_BLCH_STATUS, null,
                params, HostConstants.HTTP_METHOD_POST, LOG_NAME, baseReqObj);

        Integer code = apiResult.getInteger("code");
        String message = apiResult.getString("msg");
        if (!code.equals(0)) {
            throw new BusinessException(message, String.valueOf(code));
        }
    }

}
